package com.woniuxy.secondkill.controller;

import com.woniuxy.secondkill.utils.WebSocketUtil;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @Author zhangyong
 * @Date 2021/8/13 0013下午 3:21
 */
@RestController
@ServerEndpoint("/WebsocketController/{account}")
public class WebsocketController {
    //建立连接
    @OnOpen
    public void openSession(@PathParam("account")String account, Session session) {
        //消息
        //String message = "欢迎:"+account+"加入群聊";
        //加入聊天室
        WebSocketUtil.MESSAGEMAP.put(account, session);
        //发送消息
        //WebSocketUtil.sendMessageToAll(message);
    }

    //服务器接收到消息之后，将消息转发给所有人
    @OnMessage
    public void onMessage(@PathParam("account")String account,String message) {
        message = account+":"+message;
        WebSocketUtil.sendMessageToAll(message);
    }

    //离开聊天室
    @OnClose
    public void onClose(@PathParam("account")String account,Session session) {
        //将当前用户从map中移除 注销
        WebSocketUtil.MESSAGEMAP.remove(account);
        //群发消息
        WebSocketUtil.sendMessageToAll("用户:"+account+"离开聊天室");
        //关闭session
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //连接异常
    @OnError
    public void onError(Session session,Throwable throwable) {
        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
